package com.zt.yongxinbao.service.impl;

import com.zt.yongxinbao.dto.EmailParam;
import com.zt.yongxinbao.dto.UserRegistParam;
import com.zt.yongxinbao.entity.User;
import com.zt.yongxinbao.mapper.UserMapper;
import com.zt.yongxinbao.security.JwtTokenUtil;
import com.zt.yongxinbao.security.UserLoginDetails;
import com.zt.yongxinbao.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Iterator;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class);
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    private BCryptPasswordEncoder passwordEncoder=new BCryptPasswordEncoder();
    @Autowired
    private UserMapper userMapper;
    private User user;
    @Autowired
    private JavaMailSender javaMailSender;
    @Value("${spring.mail.username}")
    private String mailUserName;
    @Override
    public User getUserByUsername(String username) {
        User user=new User();
        user=userMapper.selectByUsername(username);
        if (user!=null) return user;
        else return null;
    }

    @Override
    public String login(String username, String password) {
        String token=null;
        //密码需要客户端加密后传递
        try {
            UserDetails userDetails = loadUserByUsername(username);
//            System.out.println((new BCryptPasswordEncoder()).matches(password,userDetails.getPassword()));
            if(!(passwordEncoder).matches(password,userDetails.getPassword())){
                throw new BadCredentialsException("密码不正确");
            }
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);
            token = jwtTokenUtil.generateToken(userDetails);
        } catch (AuthenticationException e) {
            LOGGER.warn("登录异常:{}", e.getMessage());
        }
        return token;
    }

    @Override
    public UserDetails loadUserByUsername(String username) {
        User user=getUserByUsername(username);
        if (user==null){
            throw new UsernameNotFoundException("用户名或密码错误");
        }
        return new UserLoginDetails(user);
    }
    public Integer registVaild(UserRegistParam userRegistParam){
//        /        检查用户名是否已被使用
        if(userMapper.selectByUsername(userRegistParam.getUsername())!=null){
            return 1;
        }
//       检查邮箱是否已绑定用户
        List<User> userList=userMapper.selectAllUser();
        Iterator iterator=userList.iterator();
        while (iterator.hasNext()){
            user=(User) iterator.next();
            if ((userRegistParam.getEmail()).equals(user.getEmail())){
                return 2;
            }
        }
        return 0;
    }
    @Override
    public User regist(UserRegistParam userRegistParam) {

//        将传入的对象封装为user
        User user=new User();
        user.setUsername(userRegistParam.getUsername());
        //       对密码加密
        user.setPasswordHash((passwordEncoder).encode(userRegistParam.getPassword()));
        user.setEmail(userRegistParam.getEmail());
        if (userMapper.insert(user)==1) return user;
        else{
            return null;
        }
    }

    @Override
    public Boolean updateEmail(String username, String email) {
        if (email.equals(userMapper.selectByUsername(username).getEmail())) return true;
        //       检查邮箱是否已绑定用户
        List<User> userList=userMapper.selectAllUser();
        Iterator iterator=userList.iterator();
        while (iterator.hasNext()){
            user=(User) iterator.next();
            if (email.equals(user.getEmail())){
                return false;
            }
        }
        if (userMapper.updateEmailByUsername(username,email)==1) return true;
        return false;
    }

    @Override
    public Boolean updatePassword(String username, String password) {
        String string=userMapper.selectByUsername(username).getPasswordHash();
        if (string.equals((passwordEncoder).encode(password))) return true;
        if (userMapper.updatePasswordByUsername(username,(passwordEncoder).encode(password))==1) return true;
        return false;
    }

    @Override
    public EmailParam sendMall(String email) {
        EmailParam emailParam=new EmailParam();
        SimpleMailMessage message = new SimpleMailMessage();
        int radomInt =(int)((Math.random()*9+1)*100000);
        message.setSubject("修改密码");
        message.setFrom(mailUserName);
        message.setTo(email);
        String string="您的验证码是："+radomInt+"，此验证码只能使用一次，在30分钟内有效。";
        message.setText(string);
        javaMailSender.send(message);
        emailParam.setIdentifyCode(radomInt);
        if (userMapper.selectByEmail(email)!=null) {
            emailParam.setUsername(userMapper.selectByEmail(email).getUsername());
        }
        return emailParam;
    }
}
